local yufeng = fk.CreateSkill {
  name = "md__yufeng",
}

Fk:loadTranslationTable{
  ["md__yufeng"] = "御风",
  [":md__yufeng"] = "出牌阶段限一次，你可以进行一次<a href=':md__yufeng_href'>御风飞行</a>。若失败你摸X张牌；"..
  "若成功，你可以选择至多X名其他角色，其下一个准备阶段进行一次判定：若结果为黑色，其跳过出牌和弃牌阶段；若结果为红色，" ..
  "其跳过摸牌阶段；若选择角色数不足X，剩余的分数改为摸等量张牌（X为御风飞行得分，至多为3）。",

  [":md__yufeng_href"] = "随机亮出牌堆和弃牌堆中的一张牌，然后重复猜测下一张亮出的牌比上一张亮出的牌点数更大或更小，" ..
  "直到达到分数上限或猜错（2分或3分），每猜对一次得一分。",

  ["#md__yufeng"] = "御风：你可玩令他人跳过摸牌或出牌弃牌阶段",
  ["#md__yufeng-choose"] = "御风：选择至多 %arg 名其他角色，其下回合跳过摸牌或出牌弃牌阶段",
  ["@@md__yufeng"] = "御风",
  ["#md__yufeng_delay"] = "御风",
  ["md__yufeng_more"] = "下一张牌点数比%arg大",
  ["md__yufeng_less"] = "下一张牌点数比%arg小",
  ["#md__yufeng-choice"] = "御风：猜测下一张牌的点数",
  ["score_zero"] = "惜哉，未能窥见星辰。",
  ["score_one"] = "风紧，赶紧跑。",
  ["score_not_full"] = "星辰已纳入囊中。",
  ["score_full"] = "满载而归，哈哈。",

  ["$md__yufeng1"] = "广开兮天门，纷吾乘兮玄云。",
  ["$md__yufeng2"] = "高飞兮安翔，乘清气兮御阴阳。",
}

yufeng:addEffect("active", {
  anim_type = "control",
  card_num = 0,
  target_num = 0,
  card_filter = Util.FalseFunc,
  prompt = "#md__yufeng",
  can_use = function(self, player)
    -- 出牌阶段限一次（核心：通过该函数限制每阶段仅发动一次）
    return player:usedSkillTimes(yufeng.name, Player.HistoryPhase) == 0
  end,
  on_use = function(self, room, effect)
    local player = effect.from
    -- 关键：通过usedSkillTimes获取全局总使用次数（跨回合累计）
    -- 注意：HistoryPhase参数在不同框架中可能表示“当前回合”，此处改为用全局次数计算（需确保框架支持跨回合累计）
    -- 若框架中HistoryPhase仅记录当前回合次数，可去掉该参数获取全局次数（根据实际框架调整）
    local totalUses = player:usedSkillTimes(yufeng.name, Player.HistoryGame)  -- 总使用次数（不含本次）
    local X = (totalUses == 1) and 2 or 3  -- 首次使用X=2，后续X=3

    -- 选择目标角色（至多X名）
    local tos = room:askToChoosePlayers(player, {
      targets = room:getOtherPlayers(player, false),
      min_num = 0,  -- 允许不选角色
      max_num = X,
      prompt = "#md__yufeng-choose:::" .. X,
      skill_name = yufeng.name,
      cancelable = true,
    })

    -- 对选中角色添加延迟效果标记
    if #tos > 0 then
      for _, p in ipairs(tos) do
        room:setPlayerMark(p, "@@md__yufeng", 1)  -- 保留延迟效果标记（非次数记录）
      end
    end

    -- 剩余数量转为摸牌
    local remaining = X - #tos
    if remaining > 0 then
      player:drawCards(remaining, yufeng.name)
    end
  end,
})

yufeng:addEffect(fk.EventPhaseStart, {
  anim_type = "negative",
  is_delay_effect = true,
  can_trigger = function(self, event, target, player, data)
    return target == player and player.phase == Player.Start and player:getMark("@@md__yufeng") > 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "@@md__yufeng", 0)
    local judge = {
      who = player,
      reason = yufeng.name,
      pattern = ".",
    }
    room:judge(judge)
    if judge.card.color == Card.Black then
      player:skip(Player.Play)
      player:skip(Player.Discard)
    elseif judge.card.color == Card.Red then
      player:skip(Player.Draw)
    end
  end,
})

return yufeng
